import { REQUEST } from '../type/request';
// import * as fs from 'fs';
import * as path from 'path';
import FileHelper from '../common/FileHelper';

async function getModulesDefinitions(
  modulesPath: string,
) {
  // const files = await fs.promises.readdir(modulesPath);

  const files: string[] = [];
  // 遍历获取文件夹全部文件
  FileHelper.getAllfiles(modulesPath, files);

  const parseRoute = (fileName: string) => `/${fileName.replace(/\.ts$/i, '').replace(/\.js$/i, '').replace(/_/g, '/')}`;

  const modules = files
    .reverse()
    .map((file) => file.replace(path.join(__dirname, 'modules/'), '')) // 转换为相对路径
    .filter((file) => file.endsWith('.ts') || file.endsWith('.js')) // 需要兼容打包后的代码，打包后为js文件
    .map((file) => {
      // console.log('file=', file);
      const identifier = file.split('.').shift();
      const route = parseRoute(file);
      const modulePath = path.join(modulesPath, file);
      const module = require(modulePath).default as REQUEST.BASIC;

      return { identifier, route, module };
    });
  console.log('apis=', modules.map(m => (`[${m.module.method}] ${m.route}`)));
  return modules;
}


const func = async () => {
  return getModulesDefinitions(path.join(__dirname, 'modules/'));
};

export default func;
